package main

import (
	"time"
	"fmt"
	"sync"
	"thelib"
)

/*
·开辟三条协程，A每秒生成一个三位随机数，B输出该值的奇偶性，C输出奇数和偶数的总个数；
·当生成一个水仙花数时，程序结束；(水仙花数计算方法:是指一个n位数(n≥3),它的每个位上的数字的n次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153) )
·尽量封装和抽取能复用的部分，并对它们做单元测试；
*/
var (
	wg         sync.WaitGroup
	chNumber   chan int = make(chan int, 100)
	chOddEven  chan int = make(chan int, 0)
	oddEvenMap          = make(map[string]int)
)

func init() {
	oddEvenMap["奇数"] = 0
	oddEvenMap["偶数"] = 0
}

func main() {
	wg.Add(1)
	go GenerateRandomInt()

	wg.Add(1)
	go CheckOddEven()

	wg.Add(1)
	go CountOddEven()
	//go CountOddEven()
	//go Narcissistic()

	wg.Wait()
	fmt.Println("THE END")
}

func CountOddEven() {
	for x := range chOddEven{
		if x == 0{
			oddEvenMap["偶数"]++
		}else{
			oddEvenMap["奇数"]++
		}
		fmt.Println(oddEvenMap)
	}
	wg.Done()
}

func CheckOddEven() {
	for x := range chNumber {
		if thelib.IsEven(x) {
			fmt.Printf("%d是偶数\n", x)
			chOddEven <- 0
		} else {
			fmt.Printf("%d是奇数\n", x)
			chOddEven <- 1
		}
	}

	//通知奇偶数统计协程，我不会再写入数据了
	close(chOddEven)
	wg.Done()
}

func GenerateRandomInt() {
	ticker := time.NewTicker(1 * time.Nanosecond)
	for {
		<-ticker.C
		n := thelib.CreateRandomInt(100, 999)
		fmt.Println(n)

		if thelib.IsNarcissistic(n){
			fmt.Println("生成了水仙花数",n)
			break
		}
		chNumber <- n
	}

	//通知B奇偶性判断协程，我不会再写入数据了
	close(chNumber)
	wg.Done()
}
